package com.shop.service.impl;

import com.shop.mapper.LeavebillMapper;
import com.shop.pojo.Leavebill;
import com.shop.service.LeaveBillService;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LeaveBillServiceImpl implements LeaveBillService {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    @Autowired
    private LeavebillMapper leaveBillMapper;
    // Mapper 才是实际的 @Repository


    @Override
    public void saveLeaveBill(Leavebill leavebill) {

        this.leaveBillMapper.insert(leavebill);
        // Mapper.insert(Object);
    }


    /*
     * 查询【请假单信息】
     * */
    @Override
    public Leavebill findLeaveBillByTaskId(String taskId) {

        // 1.现根据 任务id 拿到 task
        Task task = this.taskService
                .createTaskQuery()
                .taskId(taskId)
                .singleResult();

        // 2. 获取 act_ru_task.PROC_INST_ID_
        String processInstanceId = task.getProcessInstanceId();

        // 3. 获取 ProcessInstance 对象 -> act_hi_procinst -> BUSINESS_KEY_
        ProcessInstance processInstance = this.runtimeService
                .createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        // 4.获取 BUSINESS_KEY_
        //  例子：== process_key + leaveId == leaveBillProcess.28
        String businessKey = processInstance.getBusinessKey();

        // 5. 切割得到 leaveId (请假条ID)
        String leaveId = "";
        if (businessKey != null && !"".equals((businessKey))) {
            leaveId  = businessKey.split("\\.")[1];
            // 获取 split 后 [1]<--右边的
        }

        // 6.调用 Leavebill的mapper去查询出leaveBill信息
        Leavebill leavebill = this.leaveBillMapper.selectByPrimaryKey(Long.parseLong(leaveId));

        return leavebill;
    }



}
